package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("FoodbatchmaterialService")
@Transactional

public class FoodbatchmaterialServiceImpl extends CmiEmaService implements FoodbatchmaterialService {
	public FoodbatchmaterialServiceImpl() {
	}

	@Transactional
	public Foodbatchmaterial saveFoodbatchmaterial(Foodbatchmaterial foodbatchmaterial) {

		if (foodbatchmaterial.getId() == null) {
			Foodbatch foodbatch = foodbatchDAO.findFoodbatchById(foodbatchmaterial.getFoodbatch().getId());
			Material material = materialDAO.findMaterialById(foodbatchmaterial.getMaterial().getId());

			Foodbatchmaterial existingFoodbatchmaterial = foodbatchmaterialDAO
					.findFoodbatchmaterialByPhysicalPrimaryKey(foodbatch.getId(), material.getId(),
							foodbatchmaterial.getContent());

			foodbatchmaterial.setFoodbatch(foodbatch);
			foodbatchmaterial.setMaterial(material);

			if (isEquals(foodbatchmaterial, existingFoodbatchmaterial)) {
				return existingFoodbatchmaterial;
			}

			foodbatchmaterial = foodbatchmaterialDAO.store(foodbatchmaterial);
			foodbatchmaterialDAO.flush();

		} else {
			Foodbatchmaterial existingFoodbatchmaterial = foodbatchmaterialDAO
					.findFoodbatchmaterialByPrimaryKey(foodbatchmaterial.getId());

			foodbatchmaterial = foodbatchmaterialDAO.store(foodbatchmaterial);
			foodbatchmaterialDAO.flush();
		}

		return foodbatchmaterial;
	}

	public void deleteFoodbatchmaterial(Foodbatchmaterial foodbatchmaterial) {
		foodbatchmaterialDAO.remove(foodbatchmaterial);
		foodbatchmaterialDAO.flush();
	}

	@Transactional
	public void deleteFoodbatchmaterials(Set<Integer> deleteFoodbatchmaterialsId) {
		Query query = foodbatchmaterialDAO.createNamedQuery("deleteFoodbatchmaterialsById", -1, -1);
		query.setParameter(1, deleteFoodbatchmaterialsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Foodbatchmaterial> loadFoodbatchmaterials() {
		return foodbatchmaterialDAO.findAllFoodbatchmaterials();

	}

	@Transactional
	public Set<Foodbatchmaterial> loadReferenceFoodbatchmaterials(Set<Foodbatchmaterial> foodbatchmaterials) {
		Iterator<Foodbatchmaterial> foodbatchmaterialsIterator = foodbatchmaterials.iterator();
		Set<Foodbatchmaterial> referencedFoodbatchmaterials = new HashSet<>();
		while (foodbatchmaterialsIterator.hasNext()) {
			Foodbatchmaterial currentFoodbatchmaterial = foodbatchmaterialsIterator.next();

		}
		return referencedFoodbatchmaterials;
	}

	public Set<Foodbatchmaterial> loadFoodbatchmaterialsByIdSet(Set<Integer> foodbatchmaterialIdSet) {

		Iterator<Integer> foodbatchmaterialIdIterator = foodbatchmaterialIdSet.iterator();
		Set<Foodbatchmaterial> foodbatchmaterialSet = new HashSet<>();
		while (foodbatchmaterialIdIterator.hasNext()) {
			Integer id = foodbatchmaterialIdIterator.next();
			Foodbatchmaterial currentFoodbatchmaterial = foodbatchmaterialDAO.findFoodbatchmaterialById(id);
			foodbatchmaterialSet.add(currentFoodbatchmaterial);
		}
		return foodbatchmaterialSet;
	}

	@Transactional
	public List<Foodbatchmaterial> findAllFoodbatchmaterials(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Foodbatchmaterial>(
				foodbatchmaterialDAO.findAllFoodbatchmaterials(startResult, maxRows));
	}

	@Transactional
	public Foodbatchmaterial findFoodbatchmaterialByPrimaryKey(Integer id) {
		return foodbatchmaterialDAO.findFoodbatchmaterialByPrimaryKey(id);
	}

	@Transactional
	public Integer countFoodbatchmaterials() {
		return ((Long) foodbatchmaterialDAO.createQuerySingleResult("select count(o) from Foodbatchmaterial o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodbatchmaterials(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Foodbatchmaterial.class);
		return ((Long) foodbatchmaterialDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countFoodbatchmaterialsByName(String queryName) {
		Query query = foodbatchmaterialDAO.createNamedQuery("countFoodbatchmaterialsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodbatchmaterialsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Foodbatchmaterial.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFoodbatchmaterialObjectReferencedSet(Foodbatchmaterial foodbatchmaterial) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (foodbatchmaterial.getFoodbatch() != null) {

			Set<Integer> foodbatchIds = new HashSet<Integer>();
			foodbatchIds.add(foodbatchmaterial.getFoodbatch().getId());
			objectReferencedSetMap.put("foodbatchIds", foodbatchIds);
		}
		if (foodbatchmaterial.getMaterial() != null) {

			Set<Integer> materialIds = new HashSet<Integer>();
			materialIds.add(foodbatchmaterial.getMaterial().getId());
			objectReferencedSetMap.put("materialIds", materialIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFoodbatchmaterialClassReferencedSet(Foodbatchmaterial foodbatchmaterial) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("foodbatchs", foodbatchDAO.findAllFoodbatchs());
		classReferencedSetMap.put("materials", materialDAO.findAllMaterials());

		return classReferencedSetMap;
	}

	public boolean isEquals(Foodbatchmaterial foodbatchmaterial, Object obj) {
		if (obj == foodbatchmaterial)
			return true;
		if (!(obj instanceof Foodbatchmaterial))
			return false;
		Foodbatchmaterial comparedFoodbatchmaterial = (Foodbatchmaterial) obj;
		if (!CheckPropertyEqual(foodbatchmaterial.getFoodbatch().getId(),
				comparedFoodbatchmaterial.getFoodbatch().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodbatchmaterial.getMaterial().getId(),
				comparedFoodbatchmaterial.getMaterial().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodbatchmaterial.getContent(), comparedFoodbatchmaterial.getContent())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

